import axios from 'axios';
import { useConfigStore } from '@/stores/config';

const client = axios.create({
  baseURL: '/api',
  timeout: 15000
});

client.interceptors.request.use((config) => {
  const settings = useConfigStore();
  settings.loadFromStorage();
  if (settings.apiKey) {
    config.headers = {
      ...config.headers,
      'x-api-key': settings.apiKey
    };
  }
  return config;
});

client.interceptors.response.use(
  (response) => response,
  (error) => {
    const message = error.response?.data?.message || error.message;
    return Promise.reject(new Error(message));
  }
);

function adaptResponse(promise) {
  return promise.then((res) => res.data);
}

export const docsApi = {
  list: ({ params, headers } = {}) => adaptResponse(client.get('/docs', { params, headers })),
  create: ({ data, headers }) => adaptResponse(client.post('/docs', data, { headers })),
  update: (id, { data, headers }) => adaptResponse(client.put(`/docs/${id}`, data, { headers })),
  remove: (id, { headers }) => adaptResponse(client.delete(`/docs/${id}`, { headers })),
  search: ({ params, headers }) => adaptResponse(client.get('/docs/search', { params, headers })),
  searchByVector: ({ data, headers }) => adaptResponse(client.post('/docs/search', data, { headers })),
  listVectors: ({ params, headers }) => adaptResponse(client.get('/docs/vectors', { params, headers }))
};

export const aiApi = {
  rag: ({ data, headers }) => adaptResponse(client.post('/ai/rag', data, { headers }))
};

export const iconsApi = {
  list: ({ headers } = {}) => adaptResponse(client.get('/icons', { headers }))
};

export default client;
